package com.mazegame.dao;

import com.mazegame.utils.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

public class UserDao {
    // 注册用户
    public boolean register(com.mazegame.dao.User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DBUtils.getConnection();
            String sql = "INSERT INTO users (username, password, create_time) VALUES (?,?,?)";
            //INSERT INTO 插入语句 user 列表 （user，password，create_time）需要插入的字段 VALUES（？，？，？） 对应的插入的信息 ？ 占位符
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword()); // 此处暂用明文，后文会补充简单加密
            pstmt.setObject(3, LocalDateTime.now());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            return false; // 用户名重复时会触发唯一约束异常
        } finally {
            DBUtils.close(conn);
        }
    }

    // 根据用户名查询
    public User findByUsername(String username) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = DBUtils.getConnection();
            String sql = "SELECT id, password FROM users WHERE username =?";
            //SELECT 查询语句  id，password 字段 FORM 列表  WHERE 查找 username=？ 需要查找的对象 ? 占位符
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setId(rs.getLong("id"));
                user.setUsername(username);
                user.setPassword(rs.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(conn);
        }
        return null;
    }
}